package net.mlike.openssp.server.api.system;

import com.google.common.base.Strings;
import net.mlike.openssp.server.dto.Message;
import net.mlike.openssp.server.entity.system.Menu;
import net.mlike.openssp.server.search.system.menu.MenuSearch;
import net.mlike.openssp.server.service.system.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by wallellen@hotmail.com on 5/26/18.
 */
//TODO 需要角色权限控制
@RestController
@RequestMapping("/api/menus")
public class RestMenuController {
    @Autowired
    private MenuService menuService;

    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public Page<Menu> findBySearch(MenuSearch menuSearch) {
        return menuService.findBySearch(menuSearch);
    }

    @GetMapping(value = "/all", produces = MediaType.APPLICATION_JSON_VALUE)
    public List<Menu> findAll(MenuSearch menuSearch) {
        menuSearch.setPage(0);
        menuSearch.setSize(Integer.MAX_VALUE);
        return menuService.findBySearch(menuSearch).getContent();
    }

    @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
    public Message save(@RequestBody Menu menu) {
        String id = menu.getId();

        if (Strings.isNullOrEmpty(id)) {
            menuService.save(menu);
        } else {
            Menu menu1 = menuService.findById(id);
            menu1.setCode(menu.getCode());
            menu1.setIcon(menu.getIcon());
            menu1.setName(menu.getName());
            menu1.setUrl(menu.getUrl());
            menuService.save(menu1);
        }

        return Message.success();
    }

    @DeleteMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public Message delete(@PathVariable("id") String id) {
        menuService.delete(id);

        return Message.success();
    }
}
